package com.medicalfee.dao;

import java.util.List;

import org.hibernate.Session;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.medicalfee.util.HaveChineseCharacter;

public class StuffInfoDAO extends HibernateDaoSupport {
	public void insertOrUpdateStuff(StuffInfo stuffInfo) {
		this.getHibernateTemplate().saveOrUpdate(stuffInfo);
	}

	public List getStuffInfo(String hql, int startPage, int limitNum) {
		Session session = this.getSession();
		session.getTransaction().begin();
		List result = session.createQuery(hql)
				.setFirstResult((startPage - 1) * limitNum)
				.setMaxResults(limitNum).list();
		session.getTransaction().commit();
		session.close();
		return result;
	}

	public int getStuffNumber(String hql) {
		Session session = this.getSession();
		session.getTransaction().begin();
		int rowNum = session.createQuery("select count(*) " + hql)
				.uniqueResult().hashCode();
		session.getTransaction().commit();
		session.close();
		return rowNum;
	}

	public void deleteStuffInfo(String ids[]) {
		for (int i = 0; i < ids.length; i++) {
			this.getHibernateTemplate().delete(
					this.getHibernateTemplate()
							.find("from StuffInfo where id=" + ids[i]).get(0));
		}
	}

	public List findStuff(String text, int startPage, int limitNum) {
		List result;
		Session session = this.getSession();
		session.getTransaction().begin();
		if (HaveChineseCharacter.isChinese(text)) {
			result = session.createQuery("from StuffInfo where name like ?")
					.setString(0, "%" + text + "%")
					.setFirstResult((startPage - 1) * limitNum)
					.setMaxResults(limitNum).list();
		} else {
			result = session.createQuery("from StuffInfo where name like ?")
					.setString(0, text)
					.setFirstResult((startPage - 1) * limitNum)
					.setMaxResults(limitNum).list();
		}
		session.getTransaction().commit();
		session.close();
		return result;
	}

	public int getStuffNumBySearch(String text) {
		Session session = this.getSession();
		session.getTransaction().begin();
		int rowNum;
		if (HaveChineseCharacter.isChinese(text)) {
			rowNum = session
					.createQuery(
							"select count(*) from StuffInfo where name like ?")
					.setString(0, "%" + text + "%").uniqueResult().hashCode();
		} else {
			rowNum = session
					.createQuery(
							"select count(*) from StuffInfo where name like ?")
					.setString(0, text).uniqueResult().hashCode();
		}
		session.getTransaction().commit();
		session.close();
		return rowNum;
	}

	public List getStuffByHql(String hql) {
		return this.getHibernateTemplate().find(hql);
	}
}
